package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskContractBlockMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskContractBlock;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskContractBlockService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskContractBlockServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskContractBlockMapper, TaskAutotaskContractBlock>
       implements TaskAutotaskContractBlockService {

    @Override
    public void sync(ResultEntity content){
        log.debug("Auto task contractBlock receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskContractBlock data = TaskAutotaskContractBlock.builder()
                .contractBlockId(super.getLongValue(entity.get("id")))
                .isPaid(ObjectUtils.isEmpty(entity.get("isPaid"))?null : entity.get("isPaid").asBoolean())
                .hoursApproved(ObjectUtils.isEmpty(entity.get("hoursApproved"))?null : entity.get("hoursApproved").asDouble())
                .hours(ObjectUtils.isEmpty(entity.get("hours"))?null : entity.get("hours").asDouble())
                .hourlyRate(ObjectUtils.isEmpty(entity.get("hourlyRate"))?null : entity.get("hourlyRate").asDouble())
                .datePurchased(super.getDateTimeValue(entity.get("datePurchased")))
                .endDate(super.getDateTimeValue(entity.get("endDate")))
                .startDate(super.getDateTimeValue(entity.get("startDate")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskContractBlock dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskContractBlock>lambdaQuery()
                .eq(TaskAutotaskContractBlock::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskContractBlock::getContractBlockId, data.getContractBlockId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
